package com.tcxhb.job.core.schedule.workflow.retry;

import com.tcxhb.job.core.schedule.workflow.InstanceRunFlow;
import com.tcxhb.job.dao.dataobject.JobInstanceDO;
import com.tcxhb.job.dao.dataobject.JobMachineDO;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.core.constants.enums.LogActionEnum;
import com.tcxhb.job.core.schedule.execute.JobRunContext;
import com.tcxhb.job.core.schedule.router.RouterRandom;
import com.tcxhb.job.core.utils.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/12
 */
@Component
public class InstanceRunRetryFlow extends InstanceRunFlow {
    @Autowired
    private RouterRandom routerRandom;

    @Override
    public MiscResult handle(JobRunContext context) {
        for (JobInstanceDO instanceDO : context.getInstanceList()) {
            retry(instanceDO);
        }
        return MiscResult.suc();
    }

    /**
     * @param instanceDO
     * @return
     */
    public void retry(JobInstanceDO instanceDO) {
        LogUtils.info(instanceDO.getTraceId(), LogActionEnum.RetryThreadRun, "");
        //判断是否因为网络超时;或者因为网络不通
        reRouteMachine(instanceDO);
        //分发;更新状态
        MiscResult<Boolean> result = super.dispatchToAgent(instanceDO);
        //重新提交
        super.updateInstance(instanceDO, result);
    }


    /**
     * 重新加载地址
     *
     * @param instanceDO
     */
    private void reRouteMachine(JobInstanceDO instanceDO) {
        //重新获取IP地址
        List<JobMachineDO> machineList = routerRandom.routeByApp(1, instanceDO.getAppName());
        if (!CollectionUtils.isEmpty(machineList)) {
            instanceDO.setMachineAddr(machineList.get(0).httpAddress());
        }
    }
}
